import { useCallback, useEffect, useRef, useState } from 'react';

interface UseResizableProps {
  resizable?: boolean;
  minWidth?: number;
  minHeight?: number;
  maxWidth?: number;
  maxHeight?: number;
}

interface Size {
  width: number;
  height: number;
}

export function useResizable({
  resizable,
  minWidth = 520,
  minHeight = 200,
  maxWidth = window.innerWidth,
  maxHeight = window.innerHeight,
}: UseResizableProps) {
  const modalRef = useRef<HTMLDivElement>(null);
  const [size, setSize] = useState<Size>({ width: 0, height: 0 });
  const [isResizing, setIsResizing] = useState(false);
  const startPosRef = useRef({ x: 0, y: 0 });
  const startSizeRef = useRef({ width: 0, height: 0 });
  const resizeTypeRef = useRef<'right' | 'bottom' | 'corner' | null>(null);
  const isResizingRef = useRef(false);

  // 初始化时获取 Modal 的实际大小
  useEffect(() => {
    if (modalRef.current) {
      const rect = modalRef.current.getBoundingClientRect();
      // 获取实际的 Modal 内容宽度
      const modalContent = modalRef.current.querySelector('.ant-modal-body');
      const contentWidth = modalContent ? modalContent.getBoundingClientRect().width : rect.width;
      
      const initialSize = { 
        width: contentWidth, 
        height: rect.height 
      };
      console.log('Initial size:', initialSize);
      setSize(initialSize);
      startSizeRef.current = initialSize;
    }
  }, []);

  const handleResize = useCallback((e: MouseEvent) => {
    if (!isResizingRef.current || !modalRef.current) return;

    const deltaX = e.clientX - startPosRef.current.x;
    const deltaY = e.clientY - startPosRef.current.y;

    let newWidth = startSizeRef.current.width;
    let newHeight = startSizeRef.current.height;

    // 根据拖拽类型分别处理宽度和高度
    if (resizeTypeRef.current === 'right' || resizeTypeRef.current === 'corner') {
      newWidth = Math.min(
        Math.max(startSizeRef.current.width + deltaX, minWidth),
        maxWidth
      );
    }

    if (resizeTypeRef.current === 'bottom' || resizeTypeRef.current === 'corner') {
      newHeight = Math.min(
        Math.max(startSizeRef.current.height + deltaY, minHeight),
        maxHeight
      );

      // 实时更新 modal body 的高度
      const modalBody = modalRef.current.querySelector('.ant-modal-body');
      if (modalBody) {
        const header = modalRef.current.querySelector('.ant-modal-header');
        const footer = modalRef.current.querySelector('.ant-modal-footer');
        const headerHeight = header ? header.getBoundingClientRect().height : 0;
        const footerHeight = footer ? footer.getBoundingClientRect().height : 0;
        const bodyHeight = newHeight - headerHeight - footerHeight;
        
        const bodyElement = modalBody as HTMLElement;
        bodyElement.style.height = '100%';
        bodyElement.style.overflow = 'auto';
        bodyElement.style.maxHeight = `${bodyHeight}px`;
      }
    }

    // 保持之前的高度值，除非是垂直方向的调整
    if (resizeTypeRef.current === 'right') {
      newHeight = startSizeRef.current.height;
    }

    // 只有当大小确实发生变化时才更新
    if (newWidth !== size.width || newHeight !== size.height) {
      console.log('Resizing:', { 
        newWidth, 
        newHeight, 
        type: resizeTypeRef.current,
        startHeight: startSizeRef.current.height,
        currentHeight: size.height,
        deltaY,
        minHeight,
        maxHeight
      });
      setSize({ width: newWidth, height: newHeight });
    }
  }, [minWidth, minHeight, maxWidth, maxHeight, size.width, size.height]);

  const handleResizeEnd = useCallback(() => {
    setIsResizing(false);
    isResizingRef.current = false;
    resizeTypeRef.current = null;
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', handleResizeEnd);
  }, [handleResize]);

  const handleResizeStart = useCallback((e: React.MouseEvent) => {
    e.preventDefault();
    if (!modalRef.current) return;

    const target = e.target as HTMLElement;
    const resizeType = target.className.split(' ')[1] as 'right' | 'bottom' | 'corner';
    resizeTypeRef.current = resizeType;

    const rect = modalRef.current.getBoundingClientRect();
    startPosRef.current = { x: e.clientX, y: e.clientY };
    
    // 确保使用有效的初始值
    const currentWidth = size.width > 0 ? size.width : rect.width;
    const currentHeight = size.height > 0 ? size.height : rect.height;
    
    startSizeRef.current = { 
      width: currentWidth,
      height: currentHeight
    };
    
    console.log('Resize Start:', {
      type: resizeType,
      startSize: startSizeRef.current,
      currentSize: size,
      rect
    });

    setIsResizing(true);
    isResizingRef.current = true;

    document.addEventListener('mousemove', handleResize);
    document.addEventListener('mouseup', handleResizeEnd);
  }, [handleResize, handleResizeEnd, size]);

  useEffect(() => {
    if (!resizable || !modalRef.current) return;
    const modal = modalRef.current;

    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizingRef.current) {
        const rect = modal.getBoundingClientRect();
        const padding = 8;
        let cursor = '';
        if (
          e.clientX >= rect.right - padding &&
          e.clientX <= rect.right + padding
        ) {
          cursor = 'e-resize';
        } else if (
          e.clientY >= rect.bottom - padding &&
          e.clientY <= rect.bottom + padding
        ) {
          cursor = 's-resize';
        }
        modal.style.cursor = cursor;
      }
    };

    const handleMouseLeave = () => {
      if (!isResizingRef.current) {
        modal.style.cursor = '';
      }
    };

    modal.addEventListener('mousemove', handleMouseMove);
    modal.addEventListener('mouseleave', handleMouseLeave);

    return () => {
      modal.removeEventListener('mousemove', handleMouseMove);
      modal.removeEventListener('mouseleave', handleMouseLeave);
    };
  }, [resizable]);

  return {
    modalRef,
    size,
    handleResizeStart,
  };
}
